'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 祭坛奖励
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var _ = require('lodash');
var dataApi = require('../../../../libs/dataApi');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var PlayerManager = require('../../../../libs/playerManager');
var wishtreeConf = require('../../../../config/wishtreeConf');
var rewardService = require('../../../../services/rewardService');
var roleService = require('../../../../services/roleService');
var taskService = require('../../../../services/taskService');
var constantUtil = require('../../../../util/constantUtil');
var buildType = require('../../../../consts/buildType');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var wishtree_type = msg.wishtree_type;

    var wishtree_free_num = 0;
    var wishtree_buy_num;
    var next_diamond = 0;
    var crit_num = 1;

    if (!wishtree_type) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'wishtree', 'build', 'task', 'daily_task', 'achieve', 'tech', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            // jshint maxstatements:100
            function (cb) {
                var wishtree_model = player_manager.wishtree;
                var role_model = player_manager.role;
                var build_model = player_manager.build;

                // 是否购买次数达到上限
                if (!_isHaveBuyNum(player_manager, wishtree_type)) {

                    return next(null, {
                        code: Code.WISHTREE_RECEIVE_NUM_MAX
                    });
                }

                var build_item = build_model.getBuildByType(buildType.WISHTREE);

                // 资源暴击计算
                var random_num = _.random(0, 100);
                if (random_num <= constantUtil.value('wishingtree_crit_probability') && random_num >= 0) {
                    crit_num = constantUtil.value('wishingtree_crit_num');
                }

                // 发放奖励
                if (wishtree_model.getFreeWishtreeNum() > 0) {
                    var reward_list = wishtreeConf.getFreeRewardlist(wishtree_type, build_item.lv);
                    if (reward_list.need_lvl <= build_item.lv) {

                        // 扣除次数
                        wishtree_model.subFreeWishtreeNum();

                        for (var i = 0; i < crit_num; i++) {
                            rewardService.addRewardToRole(player_manager, reward_list, moduleType.MDL_WISHTREE, operationType.OPR_WISHTREE_WISH);
                        }

                        wishtree_free_num = wishtree_model.getFreeWishtreeNum();
                    } else {
                        return next(null, {
                            code: Code.WISHTREE_LV_NOT
                        });
                    }

                } else {
                    var num = wishtree_model.getWishtreeNum(wishtree_type) || 0;
                    var reward_only = wishtreeConf.getOnlyReward(wishtree_type, build_item.lv, num + 1);

                    if (wishtree_model.getFreeWishtreeNum() === 0) {
                        next_diamond = wishtreeConf.getDiamondConsumptionConf(wishtree_model.getFreeWishtreeNum() + 1);
                    }

                    if (reward_only.need_lvl <= build_item.lv) {
                        next_diamond = wishtreeConf.getDiamondConsumptionConf(num + 2);

                        if (!roleService.subDiamond(player_manager, moduleType.MDL_WISHTREE, operationType.OPR_WISHTREE_WISH, wishtreeConf.getDiamondConsumptionConf(num + 1))) {
                            return next(null, {
                                code: Code.USER_DIAMOND_NOT_ENOUGH
                            });
                        }

                        // 扣除次数
                        wishtree_model.addWishtreeNum(wishtree_type);
                        for (var j = 0; j < crit_num; j++) {
                            rewardService.addRewardToRole(player_manager, reward_only, moduleType.MDL_WISHTREE, operationType.OPR_WISHTREE_WISH);
                        }

                    } else {
                        return next(null, {
                            code: Code.WISHTREE_LV_NOT
                        });
                    }
                }
                taskService.addCompleteWishtree(player_manager);
                wishtree_buy_num = wishtree_model.getWishtreeNum(wishtree_type);
                player_manager.save(cb);
        }],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    next_diamond: next_diamond,
                    wishtree_free_num: wishtree_free_num,
                    wishtree_buy_num: wishtree_buy_num,
                    crit_num: crit_num
                }
            });
        }
    );
};

var _isHaveBuyNum = function (player_manager, wishtree_type) {
    var wishtree_model = player_manager.wishtree;
    var total_num = wishtree_model.getWishtreeTotal();
    if (wishtree_model.getFreeWishtreeNum() >= 1) {
        return true;
    } else if (total_num < constantUtil.value('wishingtree_time_limit')) {
        return true;
    } else {
        return false;
    }
};
